package net.ck.hzq;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.qmuiteam.qmui.widget.popup.QMUIPopup;

import net.ck.hzq.adapter.PosFlowedAdapter;
import net.ck.hzq.adapter.PosRecordAdapter;
import net.ck.hzq.presenter.PosRecordPresenter;
import net.ck.hzq.view.PosRecordView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

import Bean.POSSelectBean;
import Bean.POSSelectBean2;
import Bean.POSSelectParamBean;
import Utils.HelloWordModel;
import Utils.ScreenUtil;
import Utils.SystemDatas;
import activity.SelectFlowPartnerActivity;
import base.BaseActivity;
import dialog.FlowRuleDialog;
import event.DirectionalResEvent;
import event.LoginEvent;
import event.SelectFlowPartnerEvent;
import model.ListviewPosAdapter2;
import retrofit2.Call;
import retrofit2.Response;
import widget.DarkPopup;

import static com.qmuiteam.qmui.widget.popup.QMUIPopup.DIRECTION_BOTTOM;

public class PosRecordActivity extends BaseActivity implements View.OnClickListener, PosRecordView {

    private ImageView posrecord_back;

    private TextView txt_posrecord, posrecord_txt_total, posrecord_txt_jh;

    //    ListView listView;
    List<POSSelectBean.DataBean.ItemsBean> data_mpos;//MPOS
    POSSelectBean.DataBean.ItemsBean bean_mpos;
    List<POSSelectBean2.DataBean.ItemsBean> data_pos;//传统POS
    POSSelectBean2.DataBean.ItemsBean bean_pos;
    PosRecordAdapter posRecordAdapter;
    PosFlowedAdapter posFlowedAdapter;
    ListviewPosAdapter2 listviewPosAdapter2;


    private ImageView ivAdd;

    private RecyclerView myDeviceListLayout, flowedDeviceListLayout;


    private TextView myDeviceTitle, flowDeviceTitle;
    private ImageView myDeviceArrow, flowDeviceArrow;

    private int jh = 0;

    private String type;

    private SharedPreferences sp;

    private PosRecordPresenter mPresenter;

    private ArrayList<String> myDeviceNoList;
    private List<String> mSelectedDeviceNoList;
    private int mBackAmount;

    @Override
    public int getLayoutId() {
        return R.layout.activity_posrecord;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        mSelectedDeviceNoList = new ArrayList<>();

        myDeviceListLayout = findViewById(R.id.my_device_list);
        myDeviceTitle = findViewById(R.id.my_device_title);
        myDeviceArrow = findViewById(R.id.my_device_arrow);

        flowedDeviceListLayout = findViewById(R.id.flowed_device_list);
        flowDeviceTitle = findViewById(R.id.flow_device_title);
        flowDeviceArrow = findViewById(R.id.flow_device_arrow);

        findViewById(R.id.my_device_head).setOnClickListener(this);
        findViewById(R.id.flowed_device_head).setOnClickListener(this);

        myDeviceNoList = new ArrayList<>();

        sp = getSharedPreferences("ToBuy", Context.MODE_PRIVATE);

        TobuyApplication.getmInstance().onActivityCreate(this);

        posrecord_txt_total = findViewById(R.id.posrecord_txt_total);
        posrecord_txt_jh = findViewById(R.id.posrecord_txt_jh);
        posrecord_back = findViewById(R.id.posrecord_back);
        txt_posrecord = findViewById(R.id.txt_posrecord);
//        listView = (ListView) findViewById(R.id.posrecord_listview);

        type = getIntent().getStringExtra("type");//1MPOS 2传统
        if (type.equals("2")) {
            txt_posrecord.setText("传统POS查询");
        } else {
            txt_posrecord.setText("MPOS查询");
        }

        posrecord_back.setOnClickListener(this);

        ivAdd = findViewById(R.id.iv_add);
        ivAdd.setOnClickListener(this);

        mPresenter = new PosRecordPresenter(this);

        queryTPos();
    }

    private void queryTPos() {
        showProgressDialog();
        POSSelectParamBean p = new POSSelectParamBean();
        p.setCustomId(Integer.parseInt(sp.getString("id", null)));
        p.setType(type);
        Call<POSSelectBean> userMsgCall = HelloWordModel.getInstance(PosRecordActivity.this).getpos1(SystemDatas.GetService_URL
                ("getpos"), p);//, sp.getString("token", null)
        userMsgCall.enqueue(new retrofit2.Callback<POSSelectBean>() {
            @Override
            public void onResponse(Call<POSSelectBean> call, final Response<POSSelectBean> response) {
                dismissProgressDialog();
//                myDeviceListLayout.removeAllViews();
//                flowedDeviceListLayout.removeAllViews();
                try {
                    if (response.body() != null && "401".equals(response.body().getResult())) {
                        EventBus.getDefault().post(new LoginEvent());
                    } else {
                        myDeviceNoList.clear();
                        data_mpos = new ArrayList<>();

                        HashMap<String, List<POSSelectBean.DataBean.ItemsBean>> map = new HashMap<>();
                        List<POSSelectBean.DataBean.ItemsBean> myDeviceList = new ArrayList<>();

                        int openCount = 0;
                        //初始化数据
                        for (int i = 0; i < response.body().getData().getItems().size(); i++) {
                            bean_mpos = response.body().getData().getItems().get(i);
                            data_mpos.add(bean_mpos);

                            // 0-我的终端列表，2-来自别人的划拨
                            // isPassed: 4-已开通，1-未提交，2-审核中，3-审核失败，5-已激活
                            if (bean_mpos.flowStatus == 0 || bean_mpos.flowStatus == 2) {
                                myDeviceList.add(bean_mpos);
                                if ("4".equals(bean_mpos.isPassed)) {
                                    openCount += 1;
                                }
                                if ((TextUtils.isEmpty(bean_mpos.isPassed))) {
                                    myDeviceNoList.add(bean_mpos.getPosInstanceSn());
                                }
                            }

                            // 已划拨终端列表
                            if (bean_mpos.flowStatus == 1) {
                                if (map.get(bean_mpos.flowCustomId) == null) {
                                    map.put(bean_mpos.flowCustomId, new ArrayList<>());
                                }
                                map.get(bean_mpos.flowCustomId).add(bean_mpos);
                            }

                        }


                        List<String> flownameslist = new ArrayList<>();
                        Set<String> flowNames = map.keySet();
                        for (String name : flowNames) {
                            flownameslist.add(name);
                        }
                        //已划拨终端列表
                        posFlowedAdapter = new PosFlowedAdapter(PosRecordActivity.this, flownameslist, map);

                        flowedDeviceListLayout.setLayoutManager(new LinearLayoutManager(flowedDeviceListLayout.getContext())); //设置布局管理器
                        flowedDeviceListLayout.setNestedScrollingEnabled(false);//禁止滑动
                        flowedDeviceListLayout.setAdapter(posFlowedAdapter);

                        //我的终端列表
                        posRecordAdapter = new PosRecordAdapter(PosRecordActivity.this, myDeviceList);
                        myDeviceListLayout.setLayoutManager(new LinearLayoutManager(myDeviceListLayout.getContext())); //设置布局管理器
//                    myDeviceListLayout.setNestedScrollingEnabled(false);//禁止滑动
                        myDeviceListLayout.setAdapter(posRecordAdapter);
                        posrecord_txt_total.setText("终端数量: " + myDeviceList.size() + "台");
                        posrecord_txt_jh.setText("已开通: " + openCount + "台");
                    }
                } catch (Exception e) {
                }

            }

            @Override
            public void onFailure(Call<POSSelectBean> call, Throwable t) {
                dismissProgressDialog();
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.posrecord_back:
                finish();
                break;
            case R.id.my_device_head:
                myDeviceTitle.setSelected(!myDeviceTitle.isSelected());
                myDeviceArrow.setSelected(!myDeviceArrow.isSelected());
                myDeviceListLayout.setVisibility(myDeviceArrow.isSelected() ? View.VISIBLE : View.GONE);
                break;
            case R.id.flowed_device_head:
                flowDeviceTitle.setSelected(!flowDeviceTitle.isSelected());
                flowDeviceArrow.setSelected(!flowDeviceArrow.isSelected());
                flowedDeviceListLayout.setVisibility(flowDeviceArrow.isSelected() ? View.VISIBLE : View.GONE);
                break;
            case R.id.iv_add:
                showPopupMenu();
                break;
        }
    }

    private void showPopupMenu() {
        View inflate = LayoutInflater.from(this).inflate(R.layout.popup_device_flow, null);
        QMUIPopup qmuiPopup = new DarkPopup(this, DIRECTION_BOTTOM);
        qmuiPopup.setContentView(inflate);
        qmuiPopup.setPopupLeftRightMinMargin(ScreenUtil.dip2px(this, 5));
        qmuiPopup.show(ivAdd);
        inflate.findViewById(R.id.flow).setOnClickListener(v -> {
            qmuiPopup.dismiss();
            showDeviceChooseDialog(1);
        });

        inflate.findViewById(R.id.directionalallot).setOnClickListener(v -> {
            qmuiPopup.dismiss();
            showDeviceChooseDialog(2);
        });
        inflate.findViewById(R.id.rule).setOnClickListener(v -> {
            qmuiPopup.dismiss();
            mPresenter.queryRule();
        });
    }

    private void showDeviceChooseDialog(int tag) {//tag:1:终端划拨2：定向划拨
//        ChooseDeviceDialog dialog = ChooseDeviceDialog.newInstance(myDeviceNoList);
//        dialog.show(getSupportFragmentManager(), "");

        ChooseDeviceActivity.start(this, myDeviceNoList, tag);
    }

    @Subscribe
    public void registerSelectPartner(SelectFlowPartnerEvent event) {
        mSelectedDeviceNoList.clear();
        mSelectedDeviceNoList.addAll(event.mDeviceNoList);
        mBackAmount = event.backAmount;
        SelectFlowPartnerActivity.start(this, 11);
    }

    @Subscribe
    public void registerDirectionRes(DirectionalResEvent event) {
        queryTPos();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 11 && resultCode == Activity.RESULT_OK) {
            if (data != null) {
                String partnerId = data.getStringExtra("partnerId");
                if (!TextUtils.isEmpty(partnerId) && TextUtils.isDigitsOnly(partnerId)) {
                    mPresenter.flowDevices(Integer.valueOf(partnerId), mSelectedDeviceNoList, mBackAmount);
                }
            }
        }
    }

    @Override
    public void updateDevices() {
        queryTPos();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void showFlowRuleDialog(String items) {
        if (!TextUtils.isEmpty(items)) {
            FlowRuleDialog dialog = FlowRuleDialog.newInstance(items);
            dialog.show(getSupportFragmentManager(), "");
        }
    }

    @Override
    public BaseActivity getHostActivity() {
        return this;
    }

    @Override
    public void showProgress() {
        showProgressDialog();
    }

    @Override
    public void hideProgress() {
        dismissProgressDialog();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }
}
